package com.cgy.utils.base.list.stream;

import com.cgy.utils.base.json.JsonHelper;
import com.cgy.utils.base.list.ListHelper;
import com.cgy.utils.base.map.MapHelper;

import java.util.List;
import java.util.Map;

/**
 * 流式操作
 * @author CHTK
 */
public class ListStreamBuilder<T> {

    private List<T> t;
    private int size = 0;
    private Map<String, T> tempMap;
    private boolean isNull;

    public ListStreamBuilder(List<T> t) {
        this.t = t;
        this.size = ListHelper.listSize(t);
        this.tempMap = MapHelper.newMap(this.size);
    }

    /**
     * 序列化空值
     * @return
     */
    public ListStreamBuilder<T> serializeNulls() {
        this.isNull = true;
        return this;
    }
    /**
     * 添加元素
     * @param t 实体
     * @return
     */
    public ListStreamBuilder<T> add(final T t) {
        ListHelper.add(this.t, t);
        return this;
    }

    /**
     * 遍历
     * @param foreachHandler
     * @return
     */
    public ListStreamBuilder<T> foreach(final ForeachHandler<T> foreachHandler) {
        if (null != foreachHandler) {
            this.t = ListHelper.iterator(this.t, new ListHelper.IteratorHandler<T>() {
                @Override
                public T next(T t) {
                    if(isNull) {
                        return foreachHandler.next(t);
                    } else {
                        if(null != t) {
                            return foreachHandler.next(t);
                        }
                        return null;
                    }
                }
            });
        }
        return this;
    }

    /**
     * 获取list
     * @return
     */
    public List<T> toList() {
        return this.t;
    }
    /**
     * 获取Map
     * @return
     */
    public Map<String, T> toMap() {
        ListHelper.iterator(this.t, new ListHelper.IteratorHandlerCountEmpty<T>() {
            @Override
            public void next(T t, int index) {
                tempMap.put(String.valueOf(index), t);
            }
        });
        return tempMap;
    }

    /**
     * 获取 json
     * @return
     */
    public String toJson() {
        return JsonHelper.toJson(this.t);
    }

    /**
     *
     */
    public static interface ForeachHandler<T> {
        /**
         * 遍历
         *
         * @param t
         * @return
         */
        public T next(T t);
    }
}
